package com.gitee.linzl.service.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.gitee.linzl.domain.User;
import com.gitee.linzl.repository.UserRepository;

@Service
public class JpaUserDetailsServiceImpl implements UserDetailsService {
	@Autowired
	private UserRepository userRepository;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userRepository.findByUsername(username);
		if (user == null) {
			throw new UsernameNotFoundException(username);
		}
		// 暂时不管数据库存入什么，方便测试
		// 密码要从注册接口中加密保存，用Init初始化问题有点问题
		// user.setPassword(passwordEncoder.encode("fpf"));
		return user;
	}

	public static void main(String[] args) {
		PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
		String pwd = passwordEncoder.encode("fpf");
		System.out.println("pwd===" + pwd);
		System.out.println(passwordEncoder.matches("fpf", pwd));
	}
}
